<template>
  <div>
    <el-container>
      <el-header>
        <el-row :gutter='30' class='fx-header-row'>
          <el-col :offset='5' :span='1'>
            <img src='@/assets/fengye.png' alt='枫叶' height='40px' />
          </el-col>
          <el-col :span='8'>
            <el-input placeholder='请输入内容' v-model='searchStr' class='input-with-select'>
              <el-select v-model='select' slot='prepend' placeholder='请选择'>
                <el-option label='文章' value='1'></el-option>
                <el-option label='用户' value='2'></el-option>
              </el-select>
              <el-button @click='goSearchPage' slot='append' icon='el-icon-search' />
            </el-input>
          </el-col>
          <el-col :span='1'>
            <el-dropdown v-if='hasPermission' @command='handleCommand'>
              <el-avatar
                style='cursor: pointer;'
                :src='userData.avatar'
                :title='userData.userName'
                fit='contain'
                shape='square'
              />
              <el-dropdown-menu>
                <el-dropdown-item disabled>{{ userData.userName }}</el-dropdown-item>
                <el-dropdown-item command='setting'>修改资料</el-dropdown-item>
                <el-dropdown-item command='exit'>退出登录</el-dropdown-item>
                <el-dropdown-item command='logOff'>注销登录</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-col>
          <el-col :span='5'>
            <el-link href='/fxwy-login' v-if='!hasPermission'>登录</el-link>
            <el-button type='text' icon='el-icon-s-home' @click='goChat' v-if='hasPermission'>小树洞</el-button>
            <el-button type='text' icon='el-icon-edit-outline' @click='goEdit' v-if='hasPermission'>写文章</el-button>
            <el-button type='text' icon='el-icon-s-data' @click='goAdmin' v-if='isAdmin || userData?.superAdmin'>站点管理系统</el-button>
          </el-col>
        </el-row>
      </el-header>
      <el-container style='padding-top: 80px;'>
        <el-aside v-if='hasPermission' width='320px' style='height: 100vh;'>
          <UserInfo :user-data='userData' @activeTabOne='activeTabOne' />
        </el-aside>
        <el-container>
          <el-main>
            <el-tabs v-model='activeTab' @tab-click='switchTab'>
              <el-tab-pane label='广场尽览' name='articles'>
                <CommunityPage />
              </el-tab-pane>
              <el-tab-pane label='好友动态' name='myAttentionArts' v-if='hasPermission'>
                <MyAttentionArts />
              </el-tab-pane>
              <el-tab-pane label='我的文章' name='myArticles' v-if='hasPermission'>
                <MyBlogs />
              </el-tab-pane>
              <el-tab-pane label='点赞合辑' name='likes' v-if='hasPermission'>
                <LikedBlogs />
              </el-tab-pane>
              <el-tab-pane label='评论合辑' name='comments' v-if='hasPermission'>
                <MyCommented />
              </el-tab-pane>
              <el-tab-pane label='关注' name='attentions' v-if='hasPermission'>
                <MyAttention />
              </el-tab-pane>
              <el-tab-pane label='粉丝' name='fans' v-if='hasPermission'>
                <MyFans />
              </el-tab-pane>
              <el-tab-pane label='黑名单' name='blackList' v-if='hasPermission'>
                <MyBlackList />
              </el-tab-pane>
            </el-tabs>
          </el-main>
          <el-footer style='display: flex;align-items: center;justify-content: center;'>
            <GlobalFooter />
          </el-footer>
        </el-container>
      </el-container>
      <el-drawer
        v-if='userData'
        title='个人资料设置'
        :visible.sync='drawer'
        destroy-on-close
        style='z-index: 4;'
      >
        <UserSetting :user-data='userData' @close='drawer = false' />
      </el-drawer>
    </el-container>
  </div>
</template>

<script>
import AuthorizeService from '@/service/users/AuthorizeService'
import UserInfo from '@/pages/user/components/UserInfo'
import CommunityPage from '@/pages/user/components/CommunityPage'
import MyAttentionArts from '@/pages/user/components/MyAttentionArts'
import MyBlogs from '@/pages/user/components/MyBlogs'
import LikedBlogs from '@/pages/user/components/LikedBlogs'
import MyCommented from '@/pages/user/components/MyCommented'
import MyAttention from '@/pages/user/components/MyAttention'
import MyFans from '@/pages/user/components/MyFans'
import MyBlackList from '@/pages/user/components/MyBlackList'
import UserSetting from '@/pages/user/components/UserSetting'
import pageUrl from '@/config/pageUrl'
import GlobalFooter from '@/components/GlobalFooter'

export default {
  name: 'HomePage',
  components: {
    UserInfo,
    CommunityPage,
    MyAttentionArts,
    MyBlogs,
    LikedBlogs,
    MyCommented,
    MyAttention,
    MyFans,
    MyBlackList,
    UserSetting,
    GlobalFooter
  },
  data() {
    return {
      searchStr: '',
      select: '文章',
      hasPermission: false,
      drawer: false,
      isAdmin: false,
      userData: null,
      avatarUrl: '',
      currentUser: '',
      activeTab: ''
    }
  },
  created() {
    this.checkPermisson()
    this.activeTab = this.$route.params.tab ? this.$route.params.tab : 'articles'
  },
  mounted() {
    const header = document.querySelector('.el-header')
    // 监听滚轮事件
    document.addEventListener('scroll', () => {
      if (window.scrollY > 0) {
        header.classList.add('top-fixed')
      } else {
        header.classList.remove('top-fixed')
      }
    })
  },
  methods: {
    // 主页鉴权 初始化数据
    async checkPermisson() {
      let res = await AuthorizeService.checkPermission()
      if (res.data.status !== 200) {
        // 无权限就跳转到无权限的提示页面 然后跳转回登录页面
        // this.$router.push('/forbidden')
      } else {
        // 授权 允许访问本页面的基础功能
        this.hasPermission = true
        // 管理员才允许访问站点管理系统
        this.isAdmin = res.data.data.userData?.isAdmin
        // 保存用户数据
        this.userData = res.data.data.userData
        // 用户数据可能会在多个同级页面中使用 所以需要进行数据通信
        // Vuex 写法麻烦，且不易溯源，所以就不用了 事件总线也可以 但是这个项目比较小
        // 而且这个项目 用户权限的生效期就仅限于 session 期间，所以仍然采用 sessionStorage 来共享数据
        sessionStorage.removeItem('userData')
        sessionStorage.setItem('userData', JSON.stringify(this.userData))
        let currentHour = new Date().getHours()
        let title = currentHour > 5 ?
          (currentHour > 11 ?
            (currentHour > 13 ?
              (currentHour > 18 ? '晚上好'
                : '下午好')
              : '中午好')
            : '早上好')
          : '夜深了，注意休息'

        this.$notify({
          title: `${this.userData.userName}, ${title}`,
          type: 'success'
        })
      }
    },
    // 站点管理系统
    goAdmin() {
      location.replace(pageUrl.admin)
    },
    // 搜索文章或者用户
    goSearchPage() {
      if (!this.searchStr) return this.$message.warning('请输入关键字！')
      let mode = this.select === '文章' ? 'blogs' : 'users'
      this.$router.push(`/search/${mode}/${this.searchStr}`)
    },
    // 树洞聊天
    goChat() {
      if(!this.userData?.approved) {
        return this.$message.error('未审核用户禁用树洞功能！')
      }
      this.$router.push('/chatHome')
    },
    // 写文章
    goEdit() {
      if(!this.userData?.approved) {
        return this.$message.error('未审核用户禁止发布文章！')
      }
      this.$router.push('/editArticle')
    },
    // 切换 tab 组件
    switchTab(tab) {
      this.$router.push(`/home/${tab.name}`)
    },
    // 激活某个 tab
    activeTabOne(tabName) {
      this.activeTab = tabName
    },
    // 处理下拉选择
    handleCommand(command) {
      switch (command) {
        case 'setting':
          this.drawer = true
          break
        case 'exit':
          this.exit()
          break
        case 'logOff':
          this.logOff()
          break
        default:
          break
      }
    },
    // 退出
    exit() {
      sessionStorage.removeItem('authorization')
      sessionStorage.removeItem('userData')
      location.replace(pageUrl.login)
    },
    // 注销
    logOff(){
      sessionStorage.removeItem('authorization')
      sessionStorage.removeItem('userData')
      this.$router.go(0)
      this.$route.params.tab = 'articles'
    }
  }
}
</script>

<style>

.el-header {
  position: fixed;
  top: 0;
  z-index: 3;
  width: 100%;
  height: 80px !important;
  padding: 20px 0;
  margin: 0 auto;
  margin-bottom: 20px;
  border-bottom: 1px solid #ccc;
  transition: .3s;
}

.top-fixed {
  background-color: rgba(255, 255, 255, 0.8);
}

.el-select {
  width: 100px;
}

.el-input {
  margin-bottom: 0 !important;
}

.fx-header-row {
  display: flex;
  align-items: center;
}

.fx-header-row .el-col:not(.fx-header-row .el-col:nth-of-type(4)) {
  display: flex;
  justify-content: center;
}

.fx-header-row .el-col:nth-of-type(4) {
  display: flex;
  justify-content: space-evenly;
  margin-left: -15px;
}

>>> .el-aside {
  padding-left: 1%;
}

.el-drawer__open .el-drawer.rtl {
  background-color: rgb(225, 232, 231);
}

.el-avatar > img {
  width: 100%;
}

>>> .el-card__body, .el-main {
  height: 50% !important;
}
</style>
